package com.example.logindemo.config;

import com.example.logindemo.entity.RunOrder;
import com.example.logindemo.entity.User;
import com.example.logindemo.repository.RunOrderRepository;
import com.example.logindemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 应用启动时为每个用户初始化测试跑单数据
 * 同时监听用户注册事件，为新用户创建测试数据
 */
@Component
@Order(2) // 确保在用户初始化之后执行
public class RunOrderInitializer implements ApplicationRunner {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RunOrderRepository runOrderRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            initializeRunOrdersForExistingUsers();
        } catch (Exception e) {
            System.err.println("初始化跑单数据失败，但继续启动应用: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 为现有用户初始化跑单数据
     */
    @Transactional
    private void initializeRunOrdersForExistingUsers() {
        // 获取所有用户
        List<User> users = userRepository.findAll();
        
        if (users.isEmpty()) {
            System.out.println("没有用户存在，跳过跑单初始化");
            return;
        }

        System.out.println("开始为每个用户创建测试跑单数据...");
        
        int totalOrdersCreated = 0;
        for (User user : users) {
            int ordersCreated = createTestRunOrdersForUser(user);
            totalOrdersCreated += ordersCreated;
        }
        
        System.out.println("跑单初始化完成！总共为 " + users.size() + " 个用户创建了 " + totalOrdersCreated + " 个测试跑单");
    }

    /**
     * 为指定用户创建测试跑单数据
     */
    public int createTestRunOrdersForUser(User user) {
        // 检查用户是否已有跑单数据
        long existingUserOrders = runOrderRepository.countByUserId(user.getId());
        if (existingUserOrders > 0) {
            System.out.println("用户 " + user.getUsername() + " 已存在 " + existingUserOrders + " 个跑单，跳过初始化");
            return 0;
        }

        Random random = new Random();
        String[] addresses = {
            "北京市朝阳区建国门外大街1号",
            "上海市浦东新区陆家嘴环路1000号", 
            "广州市天河区珠江新城花城大道85号",
            "深圳市南山区深南大道9988号",
            "杭州市西湖区文三路478号",
            "南京市鼓楼区中山北路32号",
            "成都市高新区天府大道1388号",
            "武汉市江汉区建设大道568号"
        };
        
        String[] statuses = {"pending", "in_progress", "completed", "cancelled"};
        String[] reviewStatuses = {"unreviewed", "reviewed", "good", "excellent"};

        // 为每个用户创建2-4个测试跑单
        int orderCount = 2 + random.nextInt(3); // 2-4个订单
        
        if (orderCount <= 0) {
            System.out.println("订单数量必须大于0，跳过创建");
            return 0;
        }
        
        for (int i = 0; i < orderCount; i++) {
            RunOrder runOrder = new RunOrder();
            
            // 生成跑单ID
            String timestamp = String.valueOf(System.currentTimeMillis() + i * 1000 + user.getId() * 10000);
            String runOrderId = "R" + timestamp.substring(4) + String.format("%02d", user.getId());
            
            runOrder.setRunOrderId(runOrderId);
            runOrder.setOrderId("ORDER" + timestamp.substring(4, 12));
            runOrder.setUserId(user.getId());
            runOrder.setUserName(user.getUsername());
            runOrder.setDeliveryAddress(addresses[random.nextInt(addresses.length)]);
            runOrder.setStatus(statuses[random.nextInt(statuses.length)]);
            runOrder.setReviewStatus(reviewStatuses[random.nextInt(reviewStatuses.length)]);
            
            // 随机设置完成时间
            if ("completed".equals(runOrder.getStatus())) {
                Date completionTime = new Date(System.currentTimeMillis() - random.nextInt(Math.max(1, 7 * 24 * 60 * 60 * 1000)));
                runOrder.setCompletionTime(completionTime);
            }
            
            // 随机设置配送员
            if (!"pending".equals(runOrder.getStatus())) {
                runOrder.setDeliveryPerson("配送员" + (random.nextInt(9000) + 1000));
            }
            
            runOrder.setCreateTime(new Date(System.currentTimeMillis() - random.nextInt(Math.max(1, 30 * 24 * 60 * 60 * 1000))));
            runOrder.setUpdateTime(new Date());
            
            runOrderRepository.save(runOrder);
        }
        
        System.out.println("为用户 " + user.getUsername() + " 创建了 " + orderCount + " 个测试跑单");
        return orderCount;
    }

    /**
     * 为所有用户（包括新注册用户）创建测试跑单
     * 这个方法可以被调用来为所有没有跑单的用户创建数据
     */
    @Transactional
    public void createTestRunOrdersForAllUsers() {
        List<User> users = userRepository.findAll();
        int totalOrdersCreated = 0;
        
        for (User user : users) {
            int ordersCreated = createTestRunOrdersForUser(user);
            totalOrdersCreated += ordersCreated;
        }
        
        System.out.println("为所有用户创建测试数据完成！总共创建了 " + totalOrdersCreated + " 个跑单");
    }
}